﻿using ProtoBuf;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class Client : MonoBehaviour
{
    private Socket client;
    private const string SERVER_HOST = "192.168.0.117";
    private const int SERVER_PORT = 4123;
    private const int MSG_CACHE = 1024;

    private void Awake()
    {

    }

    private void Start()
    {
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint client_point = new IPEndPoint(IPAddress.Parse(SERVER_HOST), SERVER_PORT);

        try
        {
            client.Connect(client_point);
            Debug.Log("connect success!");
        }
        catch (Exception ex)
        {
            client.Close();
            client = null;
            Debug.Log("connect fail!");
            return;
        }

        Thread thread = new Thread(Recv);
        thread.IsBackground = true;
        thread.Start();
    }

    private void Recv()
    {
        while (true)
        {
            try
            {
                byte[] recv_cache = new byte[MSG_CACHE * MSG_CACHE];

                int length = client.Receive(recv_cache);
                Debug.Log("recv : " + Encoding.UTF8.GetString(recv_cache, 0, length));
            }
            catch (Exception ex)
            {
                client.Close();
                client = null;
                Debug.Log("server disconnect!");
            }
        }
    }

    private void Send()
    {
        if (client == null)
        {
            return;
        }

        //client.Send(Encoding.UTF8.GetBytes("send message " + UnityEngine.Random.Range(0, int.MaxValue)));
        NetModelProtocol protocol = new NetModelProtocol() { ID = 1, Commit = "heart", Message = "client heart " + UnityEngine.Random.Range(0, int.MaxValue) };
        MemoryStream ms = new MemoryStream();
        Serializer.Serialize<NetModelProtocol>(ms, protocol);
        client.Send(ms.ToArray());
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.S))
        {
            Send();
        }
    }

    private void OnDestroy()
    {
        if (client != null)
        {
            client.Close();
            client = null;
        }
    }
}
